import Ajax from '@mtjs/ajax';
import axios from 'axios';
import { Toast, Dialog } from 'vant';
import { store } from '@/store';
import { session } from '@/plugins/storage';
import { getUserToken } from './submit-token';

const instance = axios.create({
  timeout: 60 * 1000,
  maxRedirects: 3,
});
const toLoginPage = () => {
  const router = store.$router;
  if (router.currentRoute?.name !== 'login') {
    // 登录失效时，可回到第三方的首页
    const homeUrl = session.get('homeUrl') || '';
    // const site = storage.get('site') || '';
    // const newCompanyId = storage.get('newCompanyId') || '';
    const next = encodeURIComponent(homeUrl || router.currentRoute?.fullPath);
    const query = {
      next,
      // newCompanyId,
      // site,
    };
    router.replace({ name: 'login', query });
  }
};
instance.interceptors.request.use(
  function (config) {
    const token = getUserToken();
    if (token) {
      config.headers['C-Access-Token'] = token;
    } else {
      toLoginPage();
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  },
);
instance.interceptors.response.use(
  function (response) {
    const data = response.data;

    if (data?.code === 10101) {
      // 空的请求头 || token已过期
      toLoginPage();
    } else if (data.code !== 1) {
      const errData = {
        code: data.code,
        message: data.msg,
      };
      return Promise.reject(errData);
    } else {
      return data;
    }
  },
  function (error) {
    if (!error.response) return Promise.reject(error);

    // TODO: do something else when with error response

    const { data } = error.response;
    return Promise.reject(data);
  },
);

const createAjax = Ajax({
  axios: instance,
  // post请求的数据类型
  dataType: 'json',
  // 根据不同框架来显示和隐藏 Loading
  loading: {
    show: () => {
      Toast.loading({
        message: '加载中...',
        duration: 0,
        forbidClick: true,
      });
    },
    hide: () => {
      Toast.clear();
    },
  },
  // 统一的异常处理
  catch: (err = {}) => {
    // 未登录 或 登录失效
    if (err.code === 'EX_1_2_USER_01_01_007') {
      toLoginPage();
      return;
    }

    let message = (err.message || err.text || '服务器繁忙，请稍候再试').substring(0, 100);

    const isTimeOut = message.indexOf('timeout') > -1;
    const isNetworkError = message.indexOf('Network Error') > -1;

    if (isTimeOut) message = '服务响应超时';
    if (isNetworkError) message = '服务器繁忙，请稍候再试';
    Dialog.alert({ message }).then(() => {
      if (err.code === 'EX_1_2_USER_01_01_002') {
        window.history.back(-1);
      }
    });
  },
});

export default createAjax;
